package com.henu.xyh;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.henu.R;
import com.henu.tanhang.ApplicationHenu;
import com.henu.yizhiya.LoginActivity;
import com.henu.yizhiya.entity.Person;
import com.henu.zmb.DBhelper.DBhelper;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

public class MyinformationActivity extends AppCompatActivity {

    private ImageView my_image;
    private ImageButton myinformation_return;
    private LinearLayout image;
    private LinearLayout nickname;
    private LinearLayout tel;
    private LinearLayout sex;
    private TextView my_nickname_e;
    private TextView my_tel_e;
    private TextView my_sex_e;
    private TextView my_name_e;
    private Button exit;
    BmobFile bmob_File = null;
    Uri fileUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myinformation);
        myinformation_return= (ImageButton) findViewById(R.id.myinformation_return);
        myinformation_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        image= (LinearLayout) findViewById(R.id.image);

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(MyinformationActivity.this);
                dialog.setTitle("上传图片");
                dialog.setPositiveButton("从图库中选取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                        startActivityForResult(intent,1);
                    }
                }).setNegativeButton("从照相机中获取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        fileUri = getOutputMediaFileUri(0); //得到存储地址的Uri
                        //image.setImageIcon((Icon.createWithBitmap(fileUri));
                        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //此action表示进行拍照
                        i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  //指定图片的输出地址
                        startActivityForResult(i, 0);
                    }
                });
                dialog.create();
                dialog.show();
            }
        });
        Person p = BmobUser.getCurrentUser(Person.class);
        my_image = (ImageView) findViewById(R.id.my_image);
        if(!(p.getMy_image()==null||p.getMy_image().equals("")))
        {
            String url = p.getMy_image().getUrl(); // 获取地址
            DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.mipmap.ic_launcher)
                    .showImageOnFail(R.mipmap.ic_launcher)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .build();
            ImageLoader.getInstance().displayImage(url, my_image, options);

        }



        nickname= (LinearLayout) findViewById(R.id.nickname);
        nickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MyinformationActivity.this,NicknameActivity.class);
                startActivity(intent);

            }
        });
        sex= (LinearLayout) findViewById(R.id.sex);
        sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MyinformationActivity.this,SexActivity.class);
                startActivity(intent);

            }
        });
        tel= (LinearLayout) findViewById(R.id.tel);
        tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(MyinformationActivity.this,TelActivity.class);
                startActivity(intent);
            }
        });
        Person person = BmobUser.getCurrentUser(Person.class);
        my_nickname_e= (TextView) findViewById(R.id.my_nickname_e);
        my_nickname_e.setText(person.getNickname());
        my_name_e= (TextView) findViewById(R.id.my_name_e);
        my_name_e.setText(person.getUsername());
        my_tel_e= (TextView) findViewById(R.id.my_tel_e);
        my_tel_e.setText(person.getMobilePhoneNumber());
        my_sex_e= (TextView) findViewById(R.id.my_sex_e);
        my_sex_e.setText(person.getSex());
        exit= (Button) findViewById(R.id.exit);
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BmobUser.logOut();   //清除缓存用户对象
                Intent intent = new Intent(MyinformationActivity.this, LoginActivity.class);
                startActivity(intent);
                ApplicationHenu.getInstance().exit();
                finish();

            }
        });
    }

    private File createImgFile(){
        //确定文件名
        String fileName="img_"+new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date())+".jpg";
        File dir;
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            dir = Environment.getExternalStorageDirectory();
        }else{
            dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        }
        File tempFile = new File(dir,fileName);
        try{
            if(tempFile.exists()){
                tempFile.delete();
            }
            tempFile.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        //获取文件路径
        String photoPath = tempFile.getAbsolutePath();
        return tempFile;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){

            // 获取选择的图片
            Uri photoUri=data.getData();
            //获取照片路径
            String[] filePathColumn={MediaStore.Audio.Media.DATA};
            Cursor cursor=getContentResolver().query(photoUri,filePathColumn,null,null,null);
            cursor.moveToFirst();
            String path = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
            System.out.println(path+"------------");
            final BmobFile bmobFile  = new BmobFile(new File(path));
            // 在本地显示图片
            Bitmap map = BitmapFactory.decodeFile(path);
            my_image.setImageBitmap(map);
            bmobFile.uploadblock(new UploadFileListener(){
                @Override
                public void done(BmobException e) {
                    System.out.print("+++++++++++++++++++++++++++++++++++++++++图片上传成功1！");
                    // 全局变量
                    bmob_File = bmobFile;
                    DBhelper<BmobUser> db =  new DBhelper<BmobUser>();
                    Person person = BmobUser.getCurrentUser(Person.class);
                    person.setMy_image(bmob_File);
                    db.Update( person,person.getObjectId());

                    person.login(new SaveListener<Person>() {
                        @Override
                        public void done(Person person, BmobException e) {
                            if (e==null){
                                Person p = BmobUser.getCurrentUser(Person.class);
                                finish();
                            }else {
                                //登陆失败
                            }
                        }
                    });

                }
            });
        }
        if(requestCode==0){
            File file = createImgFile();
            final BmobFile bmobFile  = new BmobFile(file);
            bmobFile.uploadblock(new UploadFileListener(){
                @Override
                public void done(BmobException e) {
                    System.out.print("+++++++++++++++++++++++++++++++++++++++++图片上传成功0！");
                    bmob_File = bmobFile;
                    DBhelper<BmobUser> db =  new DBhelper<BmobUser>();
                    Person person = BmobUser.getCurrentUser(Person.class);
                    person.setMy_image(bmob_File);
                    db.Update( person,person.getObjectId());
                }
            });
        }

    }
    /** 为保存图片或视频创建一个文件地址 */
    private static Uri getOutputMediaFileUri(int type){

        return Uri.fromFile(getOutputMediaFile(type));
    }
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){

        // 首先检测外部SDCard是否存在并且可读可写
        if (!Environment.getExternalStorageState().equals("mounted")) {
            return null;
        }
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getPath());


        // 如果存储路径不存在，则创建
        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()) {
            if (! mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == 0) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else {
            return null;
        }

        return mediaFile;
    }
}
